package com.iscreen.core.services.flow;

import java.util.HashMap;
import java.util.Map;

import com.iscreen.core.trading.actions.flows.FlowImportDailyData;
import com.iscreen.core.utils.jms.JMSUtils;
import com.iscreen.utils.exceptions.IScreenException;
import com.iscreen.utils.exceptions.IScreenExceptionCodes;

public class FlowService
{
	private Map<FlowType,Flow> flows = new HashMap<FlowType, Flow>();
	
	private static FlowService instance = new FlowService();

	private void addFlow(Flow flow)
	{
		flows.put(flow.getFlowType(), flow);
	}

	public Flow getFlow(FlowType flowType)
	{
		return flows.get(flowType);
	}
	
	protected FlowService()
	{
		createFlows();
	}
	
	private void createFlows()
	{
		addFlow(new FlowImportDailyData());
	}
	public static FlowService getInstance()
	{
		return instance;
	}

	public void startFlow(FlowType flowType, Object param) throws IScreenException
	{
		Flow flow = getFlow(flowType);
		if (flow == null)
		{
			throw new IScreenException(IScreenExceptionCodes.FLOW_ERROR,"Flow " + flowType + " does not exist.");
		}
		flow.startFlow(param);
	}
	
	public void completeStep(FlowType flowType, StepType currentStep, Object stepResult) throws IScreenException
	{
		Flow flow = getFlow(flowType);
		flow.proceed(currentStep,stepResult);
	}
	
	protected void sendMessage(FlowMessage flowMessage) throws IScreenException
	{
		JMSUtils.send(flowMessage.getStep().getQueueName(), flowMessage);
	}
}
